<script
  lang="ts"
  setup
>
import { getUrlByFileNo } from '~/api/file'
import { getBookCatalogList, getbxjkxllmList, getsqbxjkList, getsxrbList } from '~/api/home'
import { splitHtmlString } from '~/composables/tts'

const title = ref('书籍展示')
const routePath = [{ name: '首页', path: '/' }, { name: title.value, path: '/peopleHealth/peopleHealthSeries' }, { name: '在线阅读', path: '' }]
const route = useRoute()
const router = useRouter()
const fileType = ref('')
const id: string = route.params.id
fileType.value = route.query.type || '长安县志'
const { collectArticleMap } = storeToRefs(useUserStore())

function toDetail() {
  navigateTo({
    path: `/peopleHealth/peopleHealthSeriesDetail/${fileType.value}`,
    query: {
      data: route.query.data,
    },
  })
}
const detail = ref({})
async function getDetail() {
  const req = {
    condition: [{
      colName: 'id',
      ruleType: 'eq',
      value: id,
    }],
  }
  let res
  switch (fileType.value) {
    case '长安县志':
      res = await getsxrbList(req)
      break

    case '西安市志':
      res = await getsqbxjkList(req)
      break

    case '西安年鉴':
      res = await getbxjkxllmList(req)
      break
  }
  console.log(res)
  if (Array.isArray(res.data) && res.data.length) {
    detail.value = res.data[0]
    return res.data[0]
  }
}
await getDetail()
const book = computed(() => {
  let result = {}
  if (fileType.value === '长安县志') {
    result = {
      bookName: detail.value?.title_name,
      publisherUnit: detail.value?.publisher,
      author: detail.value?.author,
      publishDate: detail.value?.publisher_time,
      dataSource: detail.value?.source,
      readNum: detail.value?.read_num,
      url: detail.value?.cover_file_name,
      resume: detail.value?.brief,
    }
  }
  if (fileType.value === '西安市志') {
    result = {
      bookName: detail.value?.title_name,
      publisherUnit: detail.value?.organ_name,
      author: detail.value?.author,
      publishDate: detail.value?.release_time,
      dataSource: detail.value?.origin,
      readNum: detail.value?.page_view_num,
      url: detail.value?.cover_file_name,
      resume: detail.value?.digest,
    }
  }
  if (fileType.value === '西安年鉴') {
    result = {
      bookName: detail.value?.title_name,
      publisherUnit: detail.value?.organ_name,
      author: detail.value?.create_user,
      publishDate: detail.value?.release_time,
      dataSource: detail.value?.origin,
      readNum: detail.value?.page_view_num,
      url: detail.value?.img_url,
      resume: detail.value?.digest,
    }
  }
  return result
})
const loadingCate = ref(true)
const catelog = ref([])
const currentCate = ref('')
function getCatelog() {
  getBookCatalogList(detail.value.book_no).then((res) => {
    console.log(res)
    if (res?.state === 'SUCCESS' && res.data?.length) {
      catelog.value = res.data
    }
  }).finally(() => {
    loadingCate.value = false
  })
}
getCatelog()
const currentCateContent = computed(() => {
  const text = catelog.value.find(item => currentCate.value && item.id === currentCate.value)?.content
  return text
})
// 用正则去掉html字符串中的背景颜色、文字颜色
function cleanedHtml(htmlString) {
  // 正则表达式匹配背景颜色和文字颜色
  const regex = /style="[^"]*(background-color|color):[^;]+(?:;[^"]*)?"/gi
  return htmlString.replace(regex, 'style=""')
}

const contentList = computed(() => {
  if (!currentCateContent.value) {
    return []
  }
  else {
    return splitHtmlString(cleanedHtml(currentCateContent.value))
  }
  // else {
  //   // 按500字为一项分割为数组
  //   const chunkSize = 300
  //   const text = splitHtmlString(currentCateContent.value)
  //   return text.split('').reduce((acc: string[], char: string, index: number) => {
  //     if (index % chunkSize === 0) {
  //       acc.push('')
  //     }
  //     acc[acc.length - 1] += char
  //     return acc
  //   }, [])
  // }
})
function checkCate(id) {
  currentCate.value = id
}

const pageMode = ref('仿真')

const options = ['仿真', '滚动']

const bgColor = ref('#fff')
const predefineColors = ref(['#fff', '#101010', '#BBE4BF'])
const textColorMap = {
  '#fff': '#000',
  '#101010': '#fff',
  '#BBE4BF': '#000',
}
function changeBgColor(value) {
  bgColor.value = value
}
const playing = ref(false)
const bgAudio = ref(null)
function togglePlaying() {
  playing.value = !playing.value
  if (playing.value) {
    bgAudio.value.play()
  }
  else {
    bgAudio.value.pause()
  }
}
onMounted(() => {
  nextTick(() => {
    if (bgAudio.value) {
      togglePlaying()
    }
  })
})
</script>

<template>
  <div class="py-5%">
    <ClientOnly>
      <CommonPageContainer :title="title" :path="routePath">
        <div class="px-5">
          <div class="min-h-600px rounded-2xl bg-#F7F4EF px-6.5 py-5">
            <div
              class="float-left ml-[-50px] h-40px w-40px flex cursor-pointer items-center justify-center rounded-md"
              style="background: linear-gradient(159.97deg, rgba(206,234,158,1) -140.78%,#AC8358 89.45%);"
              @click="router.back()"
            >
              <div class="h-18px w-18px flex items-center justify-center rounded-50% bg-#fff">
                <span class="flex items-center -ml-2px" text="#AC8358">
                  <i class="i-ri:arrow-left-s-line" />
                </span>
              </div>
            </div>
            <div class="my-2 text-1.2rem text-#AC8358 font-700 line-height-8">
              {{ book?.bookName ?? '暂无数据' }}
            </div>
            <div class="min-h-[calc(600px_-_50px)] flex gap-10px">
              <div class="h-full min-h-600px w-300px rounded-8px bg-white p-18px">
                <div
                  class="mb-10px h-54px w-full rounded-4px p-15px text-#977D6A" flex="~ items-center"
                  bg="[url(/img/catebg.png)] no-repeat cover"
                >
                  <i class="i-ri:apps-fill mr-5px" /> 目录
                </div>
                <div>
                  <div
                    :class="currentCate === '封面' ? 'text-#AC8358 font-bold bg-#FAF5EE b-y-#E2D6C5' : ''"
                    class="h-45px cursor-pointer truncate px-30px line-height-45px" border="1px solid transparent"
                    @click="checkCate('封面')"
                  >
                    封面
                  </div>
                  <div
                    v-for="cate in catelog" :key="cate.id"
                    :class="currentCate === cate.id ? 'text-#AC8358 font-bold bg-#FAF5EE b-y-#E2D6C5' : ''"
                    class="h-45px cursor-pointer truncate px-30px line-height-45px" border="1px solid transparent"
                    @click="checkCate(cate.id)"
                  >
                    {{ cate.contents_name || '' }}
                  </div>
                </div>
              </div>
              <div v-if="detail?.cover_file_name" class="h-full min-h-600px flex-1 rounded-8px bg-white p-18px">
                <div v-if="currentCate === '封面'" class="h-full w-full flex justify-center overflow-hidden">
                  <el-image :src="getUrlByFileNo(detail.cover_file_name)" class="h-full" :lazy="true" />
                </div>
                <div v-else-if="currentCate && currentCateContent" :key="currentCate">
                  <div class="flex items-center">
                    <div class="custom-style">
                      <span class="mr-10px text-14px">翻页模式</span>
                      <el-segmented v-model="pageMode" :options="options" />
                    </div>
                    <div class="ml-40px flex items-center">
                      <span class="mr-10px text-14px">
                        背景色
                      </span>
                      <div
                        v-for="item in predefineColors" :key="item"
                        border="2px solid"
                        :class="{ 'b-#B78C61': bgColor === item }"
                        class="mr-10px h-20px w-20px rounded-50%" :style="{ backgroundColor: item, borderColor: item === bgColor ? '#B78C61' : '#ccc' }" @click="changeBgColor(item)"
                      />
                      <!-- <el-color-picker v-model="bgColor" show-alpha :predefine="predefineColors" /> -->
                    </div>
                    <div class="flex flex-1 justify-end">
                      <div class="h-30px w-30px text-center line-height-30px" :class="{ 'record-spin': playing }" @click="togglePlaying">
                        <i class="i-ri:music-2-fill cursor-pointer text-#B78C61" />
                        <audio ref="bgAudio" src="/media/bg1.mp3" />
                      </div>
                    </div>
                  </div>
                  <div v-if="pageMode === '仿真'" class="book-wrap w-full w-full flex items-center justify-center p-20px">
                    <TurnBook v-if="contentList && contentList.length" :w="700" :h="500">
                      <div class="book-item h-full w-full overflow-hidden p-10px" :style="{ backgroundColor: bgColor, color: textColorMap[bgColor] }">
                        <el-image :src="getUrlByFileNo(detail.cover_file_name)" class="pointer-events-none h-full w-full select-none" />
                      </div>
                      <div v-for="(item, index) in contentList" :key="index" class="page" :style="{ backgroundColor: bgColor, color: textColorMap[bgColor] }">
                        <div class="book-item h-full w-full overflow-hidden p-20px shadow-[0px_2px_10px_0px_rgba(151,125,106,0.2)]" v-html="item" />
                      </div>
                      <!-- <div class="book-item h-full w-full flex items-center justify-center overflow-hidden p-10px text-40px" :style="{ backgroundColor: bgColor, color: textColorMap[bgColor] }">
                        完
                      </div> -->
                    </TurnBook>
                  </div>
                  <div v-else class="p-10px">
                    <div class="h-500px overflow-auto p-10px shadow-[0px_2px_10px_0px_rgba(151,125,106,0.2)]" :style="{ backgroundColor: bgColor, color: textColorMap[bgColor] }">
                      <div class="line-height-2em" v-html="cleanedHtml(currentCateContent)" />
                    </div>

                    <!-- <div v-if="currentCateContent" class="h-500px h-full" v-html="currentCateContent" /> -->
                  </div>
                  <div class="itms-center mt-30px flex justify-center">
                    <div
                      class="mr-14px h-42px w-100px flex cursor-pointer items-center justify-center rounded-8px bg-white text-#D4AF95"
                      border="1px solid #E2D6C5"
                      @click="changeArticleCollect(detail.uid)"
                    >
                      <i
                        class="i-carbon:favorite-filled mr-12px inline-block text-20px"
                        :class="{ 'text-red': collectArticleMap[detail.uid] }"
                      />
                      <span class="text-black">{{ collectArticleMap?.[detail.uid] ? '已收藏' : '收藏' }}</span>
                    </div>
                    <div
                      class="h-42px w-100px flex cursor-pointer items-center justify-center rounded-8px bg-white text-#D4AF95"
                      border="1px solid #E2D6C5"
                      @click="copyUrl"
                    >
                      <i class="i-ri:share-fill mr-12px" />
                      <span class="text-black">分享</span>
                    </div>
                  </div>
                </div>
                <div v-else-if="currentCate && !currentCateContent">
                  <el-empty />
                </div>
              </div>
            </div>
          </div>
        </div>
      </CommonPageContainer>
    </ClientOnly>
  </div>
</template>

<style
  lang="scss"
  scoped
>
.custom-style .el-segmented {
  --el-segmented-item-selected-color: #fff;
  --el-segmented-item-selected-bg-color: #b78c61;
  --el-border-radius-base: 4px;
}
.book-wrap {
  /* background-image: url('/img/spine.png'); */
  /* background-repeat: repeat-y; */
  /* background-position: center; */
}
.book-item {
  /* background-image: url('/img/bookpages.png'); */
}
@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.record-spin {
  animation: rotate 5s linear infinite;
}
</style>
